<template>
  <div
    class="practice-box"
    v-show="emitVis && showTaskList.length"
    @mouseleave="isShow = false"
  >
    <el-badge :value="count" class="item" type="warning">
      <div class="basket-icon-box">
        <img
          class="img hover"
          @mouseenter="isShow = true"
          @click="toTopicDetail"
          src="@/assets/images/assignment/basket.png"
        />
      </div>
    </el-badge>
    <div class="basket-box" :class="[isShow ? 'fade-in' : 'fade-out']">
      <div class="title flex-between">
        已选({{ taskList.length }})
        <span class="clear" @click="onReset">清空</span>
      </div>
      <div class="list-box flex-column">
        <div class="flex line line-header">
          <div class="line-item">已选题型</div>
          <div class="line-item">数量</div>
          <div class="line-item">操作</div>
        </div>
        <div class="content flex-column">
          <div class="flex-center" v-if="!showTaskList.length">暂无习题</div>
          <div
            class="flex line"
            v-for="(task, index) in showTaskList"
            :key="index"
          >
            <div class="line-item">{{ questionTypeMap[task.topic_type] }}</div>
            <div class="line-item">{{ task.list.length }}</div>
            <div class="line-item">
              <button
                class="delete-btn"
                type="primary"
                size="small"
                @click="onDeleteTopic(task)"
              >
                删除
              </button>
            </div>
          </div>
        </div>
      </div>
      <div class="btn-box">
        <button class="gen-paper-btn" @click="onGenPaper">生成试卷</button>
        <button class="submit-btn" @click="onPublish">发布</button>
      </div>
    </div>
  </div>
  <TaskDrawer v-if="taskVisible" :task-type="2" v-model:visible="taskVisible" />
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useTaskStore, useAuthStore } from '@/stores'
import { storeToRefs } from 'pinia'
import TaskDrawer from './TaskDrawer.vue'
import { ElMessage } from 'element-plus'
import { questionTypeMap } from '@/constants/subject-map'
import { postGenPaper, postUseQuestionList } from '@/apis/assignment/index'
import router from '@/router'
import { iframeTaskMitt } from '@/utils/tools/bus'

const isShow = ref(false)

const taskStore = useTaskStore()
const authStore = useAuthStore()
const { taskList } = storeToRefs(taskStore)
const count = computed(() => taskList.value.length)

const taskVisible = ref(false)

const onGenPaper = async () => {
  const map = new Map()
  taskList.value.forEach(e => {
    if (map.has(e.topic_type)) {
      const list = map.get(e.topic_type)
      list.push({
        qid: e.question_detail.id,
        qst: e.question_detail,
        source: 11
      })
    } else {
      map.set(e.topic_type, [
        {
          qid: e.question_detail.id,
          qst: e.question_detail,
          source: 11
        }
      ])
    }
  })
  const children = []
  for (const val of map.values()) {
    children.push({
      name: val[0].qst.question_type,
      qst: val
    })
  }
  const { code, data } = await postGenPaper({
    grade: authStore.nowGlobalStageId,
    course_id: authStore.nowGlobalCourseId,
    enter_type: 3,
    source: 11,
    children
  })
  if (code === 10000) {
    // 提交题目引用次数
    postUseQuestionList({
      question_id: taskList.value.map(item => item.topic_id)
    })

    onReset()
    router.push({
      path: '/question-bank/resource-center/paper/edit',
      query: {
        id: data.id,
        completion_status: 1,
        source: 11,
        from: 'ai-learn'
      }
    })
  } else {
    ElMessage.error('生成试卷失败！')
  }
}

const onPublish = () => {
  if (!taskList.value.length) {
    ElMessage.error('请先选择习题')
    return
  }
  if (
    taskList.value.some(item => item.totalScore) &&
    !taskList.value.every(item => item.totalScore)
  ) {
    ElMessage.error('不能有分数为0的题目，请先设置分数！')
    return
  }
  taskVisible.value = true
}
const onDeleteTopic = topic => {
  taskStore.onDeleteTopic(topic.topic_type)
}

const onReset = () => {
  taskStore.reset()
}

const toTopicDetail = () => {
  let url = router.resolve({
    name: 'taskDetail'
  })
  isShow.value = false
  window.open(url.href, '_blank')
}

const showTaskList = computed(() => {
  let list = []
  taskList.value.forEach(item => {
    let index = list.findIndex(child => child.topic_type === item.topic_type)
    if (index !== -1) {
      list[index].list.push(item)
    } else {
      list.push({
        topic_type: item.topic_type,
        list: [item]
      })
    }
  })
  return list
})

const emitVis = ref(true)

const initData = () => {
  iframeTaskMitt.on('toggle-topic-selector-dialog', bool => {
    console.log('接收消息', bool)
    emitVis.value = !bool
  })
  iframeTaskMitt.on('on-publish-or-gen-paper', type => {
    console.log('type', type)
    if (type === 'publish') {
      onPublish()
    } else {
      onGenPaper()
    }
  })
}

onMounted(() => {
  initData()
})
</script>

<style lang="less" scoped>
.practice-box {
  position: fixed;
  top: 50%;
  right: 0;
  transform: translateY(-50%);
  width: 64px;
  height: 100px;
  z-index: 999;

  :deep(.el-badge__content) {
    right: unset;
    left: 0;
    transform: translate(-50%, -50%);
  }

  .basket-icon-box {
    background-color: #3d54d9;
    box-shadow: 0px 4px 11.7px 0px #ced9f5;
    border-radius: 8px;
    width: 65px;
    height: 65px;
    display: flex;
    justify-content: center;
    align-items: center;

    .img {
      width: 40px;
    }
  }

  .img {
    position: relative;
  }

  .basket-box {
    width: 334px;
    max-height: 428px;
    right: 64px;
    position: absolute;
    top: -50%;
    border-radius: 14px 0 0 14px;
    box-shadow: 0 3.26px 16.32px 0 #abb7c699;
    padding: 20px;
    box-sizing: border-box;
    background-color: #fff;
    display: none;

    .title {
      margin-bottom: 20px;
      font-size: 16px;
      font-weight: 700;

      .clear {
        cursor: pointer;
        color: #ff6d65;
        font-size: 14px;
      }
    }

    .list-box {
      gap: 10px;
      width: 100%;

      .content {
        overflow-y: auto;
        max-height: 200px;
        gap: 10px;
      }

      .line-header {
        background-color: #f7f9ff;
        border-radius: 3px;
        padding: 10px 0;
        font-size: 14px;
        font-weight: 500;
        color: rgba(4, 11, 26, 0.8) !important;
      }

      .line {
        padding: 8px 0;
        color: rgba(4, 11, 26, 0.6);
        font-size: 14px;

        .line-item {
          flex: 1;
          text-align: center;

          :deep(.el-button--primary) {
            background-color: #e9eeff;
            color: #5466e7;
            border: unset;
          }
        }
      }

      .delete-btn {
        cursor: pointer;
        border: unset;
        border-radius: 4px;
        padding: 4px 10px;
        font-size: 14px;
        color: @color-brand-regular;
        background-color: rgba(66, 143, 255, 0.06);
      }
    }

    .btn-box {
      display: flex;
      margin-top: 10px;
      gap: 20px;

      .gen-paper-btn,
      .submit-btn {
        flex: 1;
        border-radius: 5px;
        padding: 7px 0;
        font-size: 14px;
        font-weight: 500;
      }

      .gen-paper-btn {
        color: #428fff;
        border: 1px solid #428fff;
        background-color: #fff;
        &:hover {
          background-color: #ecf5ff;
        }
      }

      .submit-btn {
        border: unset;
        background-color: @color-brand-regular;
        color: #fff;

        &:hover {
          background-color: @color-brand-checked;
        }
      }
    }
  }

  .fade-out {
    animation: fade-out 400ms;
  }

  .fade-in {
    display: block;
    animation: fade-in 300ms;
  }
}
</style>
